<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

class AutogeneratorControllerFields extends JControllerAdmin {

    /**
     *
     * @var AutogeneratorModelField 
     */
    public $oModelField;

    public function __construct($arConfig = array()) {
        parent::__construct($arConfig);

        $this->oModelField = $this->getModel();
    }

    public function getModel($strName = 'Field', $strPrefix = 'AutogeneratorModel', $arConfig = array('ignore_request' => true)) {
        return parent::getModel($strName, $strPrefix, $arConfig);
    }

    public function saveOrderAjax() {
        $pks = $this->input->post->get('cid', array(), 'array');
        $order = $this->input->post->get('order', array(), 'array');

        // Sanitize the input
        JArrayHelper::toInteger($pks);
        JArrayHelper::toInteger($order);

        // Save the ordering
        $return = $this->oModelField->saveorder($pks, $order);

        if ($return) {
            echo "1";
        }
        
        // Close the application
        JFactory::getApplication()->close();
    }

    public function detectXMLType()
    {
        $oDb = JFactory::getDbo();
        $oQuery = $oDb->getQuery(true);
        
        $aFieldId = $this->input->post->get('cid', array(), 'array');
        
        foreach($aFieldId as $iFieldId)
        {
            $iXMLTypeId = $this->oModelField->detectXMLType($iFieldId);
            if ($iXMLTypeId)
            {
                $oQuery->clear()
                        ->update($oDb->quoteName('#__auto_field'))
                        ->set($oDb->quoteName('xml_type_id') . ' = ' . (int) $iXMLTypeId)
                        ->where($oDb->quoteName('id') . ' = ' . $oDb->quote($iFieldId));
                
                $oDb->setQuery($oQuery);
                try
                {
                    $oDb->execute();
                }
                catch (RuntimeException $e)
                {
                    JError::raiseWarning(500, $oDb->getMessage());
                    return false;
                }
            }
        }
        JFactory::getApplication()->redirect('index.php?option=com_autogenerator&view=fields', JText::_('COM_AUTOGENERATOR_FIELDS_DETECT_XML_TYPE_SUCCESS'), 'message');
    }
    
}
